// #include"mock_C++_thread.hpp"
#include <unistd.h>
#include "C++_mutex.hpp"

int counter = 100;
pthread_mutex_t mutex;
pthread_cond_t cond;

void *start_routine(void *args)
{
    thread_mutex _mutex(&mutex);
    while (true)
    {
        _mutex.lock();
        if (counter > 0)
        {
            pthread_cond_wait(&cond, &mutex);
            counter--;
            std::cout << "抢票用户：" << (char *)args << " 剩余票数: " << counter << std::endl;
            _mutex.unlock();
            // usleep(1234);
        }
        else
        {
            _mutex.unlock();
            break;
        }
    }

    return nullptr;
}

int main()
{
    pthread_t thread_1, thread_2;
    cond = PTHREAD_COND_INITIALIZER;
    char name_1[] = "抢票选手1";
    char name_2[] = "抢票选手2";

    pthread_create(&thread_1, NULL, start_routine, (void *)name_1);
    pthread_create(&thread_2, NULL, start_routine, (void *)name_2);

    while (true)
    {
        pthread_cond_signal(&cond);
        sleep(1);
    }

    pthread_join(thread_1, NULL);
    pthread_join(thread_2, NULL);

    return 0;
}

// int counter = 10;
// pthread_mutex_t mutex;

// void* start_routine(void* args)
// {
//     while(true){

//         pthread_mutex_lock(&mutex);
//         if (counter > 0){
//             counter--;

//             pthread_mutex_unlock(&mutex);
//             usleep(1234);
//             std::cout << "抢票用户："<< (char*) args << " 剩余票数: " << counter << std::endl;
//         }
//         else{
//             pthread_mutex_unlock(&mutex);
//             break;
//         }
//     }

//     return nullptr;
// }

// int main()
// {
//    pthread_t thread;
//    char buff[] = "次线程";
//    char name[] = "主线程";
//    pthread_mutex_init(&mutex, NULL);
//    pthread_create(&thread, NULL, start_routine, (void*)buff);

//    start_routine((void*)name);

//     pthread_join(thread, NULL);

//     return 0;
// }

// 主线程和子线程的界限
//    usleep(14);